package com.gitee.hljdrl.utils.date;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.Calendar;
import java.util.Date;

public class CalendarUtils {


    public static Calendar getInstance(@Nullable Date date) {
        Calendar calendar = Calendar.getInstance();
        if (date != null) {
            calendar.setTime(date);
        }

        copyDateTo(calendar, calendar);
        return calendar;
    }

    @NonNull
    public static Calendar getInstance() {
        Calendar calendar = Calendar.getInstance();
        copyDateTo(calendar, calendar);
        return calendar;
    }

    public static void setToFirstDay(Calendar calendar) {
        int year = getYear(calendar);
        int month = getMonth(calendar);
        calendar.clear();
        calendar.set(year, month, 1);
    }

    public static void copyDateTo(Calendar from, Calendar to) {
        int year = getYear(from);
        int month = getMonth(from);
        int day = getDay(from);
        to.clear();
        to.set(year, month, day);
    }

    public static int getYear(Calendar calendar) {
        return calendar.get(1);
    }

    public static int getMonth(Calendar calendar) {
        return calendar.get(2);
    }

    public static int getDay(Calendar calendar) {
        return calendar.get(5);
    }

    public static int getMonthDay(Calendar calendar) {
        StringBuffer _buf = new StringBuffer();
        _buf.append(getMonth(calendar));
        int _day = getDay(calendar);
        if (_day < 10) {
            _buf.append(0);
        }

        _buf.append(_day);
        int _formatValue = Integer.parseInt(_buf.toString());
        return _formatValue;
    }

    public static int getHour(Calendar calendar) {
        return calendar.get(11);
    }

    public static int getMinute(Calendar calendar) {
        return calendar.get(12);
    }

    public static int getDayOfWeek(Calendar calendar) {
        return calendar.get(7);
    }

    public static int getDayOfWeekInMonth(Calendar calendar) {
        return calendar.get(8);
    }

    public static void copyDateToHour(Date from, Calendar to) {
        Calendar fromCalendar = getInstance(from);
        to.set(11, getHour(fromCalendar));
        to.set(12, getMinute(fromCalendar));
    }
}
